import React, { memo, useState, useCallback, useRef } from 'react'

const HYIncrement = memo((props) => {
  console.log('HYIncrement重新渲染')
  const {incrementHandle} = props;
  return (
    <div>
      <button onClick={incrementHandle}>+1</button>
    </div>
  )
})

const App = memo(() => {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('hello');
  /**
   * 1.useCallback(fn, deps) 相当于 useMemo(() => fn, deps)。
   * 2.用于缓存函数，避免不必要的重新渲染
   * 3.当参数二发生变化时，才会重新创建函数
   */
/*   const increment = useCallback(() => {
    setCount(count + 1);
  }, [count]); */
  const countRef = useRef();
  countRef.current = count;
  const increment = useCallback(() => {
    setCount(countRef.current + 1);
  }, []);
  return (
    <div>
      <p>计数: {count}</p>
      <button onClick={increment}>+1</button>
      <HYIncrement incrementHandle={increment}></HYIncrement>
      <div>
        <p>{message}</p>
        {/* 修改message 不会导致 HYIncrement 组件的更新 */}
        <button onClick={e=>setMessage('hello word')}>修改message</button>
      </div>
    </div>
  )
})

export default App